package com.qm.console.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qm.console.controller.response.BaseResponse;
import com.qm.console.model.SysPermission;
import com.qm.console.model.SysRole;
import com.qm.console.model.UserInfo;
import com.qm.console.service.SysPermissionService;
import com.qm.console.service.SysRolePermissionService;
import com.qm.console.service.SysUserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/permission")
public class SysPermissionController {

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    SysPermissionService sysPermissionService;

    @Autowired
    SysRolePermissionService sysRolePermissionService;

    /**
     * 权限树状结构.
     *
     * @return
     */
    @RequestMapping(value = "/permissionList", method = RequestMethod.GET)
    public JSONObject permissionTree() {
        List<SysPermission> allPermissions = sysPermissionService.listAllByLevel();
        if (allPermissions.isEmpty()) {
            return new JSONObject();
        }
        int currentLevel = allPermissions.get(0).getLevel();
        Map<Integer, JSONArray> currentLevelMap = new HashMap<>();
        Map<Integer, Map<Integer, JSONArray>> childrenMap = new HashMap<>();
        for (SysPermission sysPermission : allPermissions) {
            if (currentLevel != sysPermission.getLevel()) {
                childrenMap.put(sysPermission.getLevel(), currentLevelMap);
                currentLevelMap = new HashMap<>();
                currentLevel = sysPermission.getLevel();
            }
            JSONArray parentChildren = currentLevelMap.get(sysPermission.getParentId());
            if (parentChildren == null) {
                parentChildren = new JSONArray();
                currentLevelMap.put(sysPermission.getParentId(), parentChildren);
            }
            Map<Integer, JSONArray> currentChildrenMap = childrenMap.get(sysPermission.getLevel());
            JSONObject itemJson = new JSONObject();
            itemJson.put("id", sysPermission.getId());
            itemJson.put("label", sysPermission.getName());
            if (currentChildrenMap != null) {
                JSONArray children = currentChildrenMap.get(sysPermission.getId());
                if (children != null) {
                    itemJson.put("children", children);
                }
            }
            parentChildren.add(itemJson);
        }
        if (currentLevelMap.isEmpty()) {
            return new JSONObject();
        }
        JSONObject result = new JSONObject();
        result.put("items", currentLevelMap.get(0));
        return new BaseResponse<>(result);
    }

    /**
     * 菜单树状结构.通过勾选的权限生成
     *
     * @return
     */
    @RequestMapping(value = "/menuList", method = RequestMethod.GET)
    public JSONObject menuTree() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println("=============" + subject.toString());
        int uid = ((UserInfo) subject.getPrincipal()).getUid();
        // 或者这个用户的所有权限ID
        List<SysRole> sysRoleList = sysUserRoleService.getSysRoleByUid(uid);
        HashSet<Integer> permissionIdSet = new HashSet<Integer>();
        for (SysRole sysRole : sysRoleList) {
            List<SysPermission> sysPermissionsList = sysRolePermissionService.getSysPermissionsByRoleId(sysRole.getId());
            for (SysPermission sysPermission : sysPermissionsList) {
                permissionIdSet.add(sysPermission.getId());
            }
        }
        return listMenus(permissionIdSet);
    }

    private JSONObject listMenus(HashSet<Integer> permissionIdSet) {
        List<SysPermission> allPermissions = sysPermissionService.listAllByLevel(2);
        if (allPermissions.isEmpty()) {
            return new JSONObject();
        }
        int currentLevel = allPermissions.get(0).getLevel();
        Map<Integer, JSONArray> currentLevelMap = new HashMap<>();
        Map<Integer, Map<Integer, JSONArray>> childrenMap = new HashMap<>();
        for (SysPermission sysPermission : allPermissions) {
            if (!permissionIdSet.contains(sysPermission.getId())) {
                continue;
            }
            if (currentLevel != sysPermission.getLevel()) {
                childrenMap.put(sysPermission.getLevel(), currentLevelMap);
                currentLevelMap = new HashMap<>();
                currentLevel = sysPermission.getLevel();
            }
            JSONArray parentChildren = currentLevelMap.get(sysPermission.getParentId());
            if (parentChildren == null) {
                parentChildren = new JSONArray();
                currentLevelMap.put(sysPermission.getParentId(), parentChildren);
            }
            Map<Integer, JSONArray> currentChildrenMap = childrenMap.get(sysPermission.getLevel());
            JSONObject itemJson = new JSONObject();
            JSONObject meta = new JSONObject();
            itemJson.put("path", sysPermission.getPath());
            itemJson.put("name", sysPermission.getName());
            itemJson.put("autoRoute", sysPermission.getAutoRoute());
            itemJson.put("pageId", sysPermission.getId());
            itemJson.put("meta", meta);
            meta.put("icon", sysPermission.getIcon());
            if (sysPermission.getId() == 1)
                {
                    itemJson.put("noDropdown", true);
            }
            if (currentChildrenMap != null) {
                JSONArray children = currentChildrenMap.get(sysPermission.getId());
                if (children != null) {
                    itemJson.put("children", children);
                }
            }
            parentChildren.add(itemJson);
        }
        if (currentLevelMap.isEmpty()) {
            return new JSONObject();
        }
        JSONObject result = new JSONObject();
        result.put("items", currentLevelMap.get(0));
        return new BaseResponse<>(result);
    }

}
